<template>
  <input type="file" id="file" ref="file" :accept="props.accept" @change="getFile" />

  <div class="upload">
    <div>
      <slot name="btn">
        <div class="left" @click="chooseFile">
          <svg-icon icon="upload" class-name="upload-icon"></svg-icon>
        </div>
      </slot>
    </div>
    <div class="right">
      <slot name="right">
        <div>仅支持{{ toUpper(props.accept) }} 类型文件上传</div>
      </slot>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ElMessage } from 'element-plus'
  import { toUpper } from 'lodash'

  const props = defineProps({
    accept: {
      type: String,
      default: '.jepg,.png'
    },
    maxSize: {
      type: Number,
      default: 10
    }
  })
  const { maxSize, accept } = toRefs(props)
  const file = ref()

  const chooseFile = () => {
    file.value.click()
  }
  const emit = defineEmits(['getFils'])

  const getFile = (e: any) => {
    const file = e.target.files[0]

    if (!file) return

    if (!accept.value.split(',').some((item) => file.name.indexOf(item) !== -1)) {
      ElMessage.warning('文件类型错误，请重新选择！')
      return
    }

    if (file.szie > maxSize.value * 1024 * 1024) {
      ElMessage.warning('文件不能超过' + maxSize.value + 'M，请重新选择！')
      return
    }
    emit('getFils', file)
  }
</script>
<style lang="scss" scoped>
  #file {
    display: none;
  }
  .upload {
    display: flex;
    .left {
      width: 74px;
      height: 74px;
      border: 1px dashed var(--el-border-color);
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        cursor: pointer;
        border-color: var(--el-color-primary);
      }

      .upload-icon {
        width: 32px;
        height: 32px;
      }
    }
    .right {
      margin-left: 18px;
      div {
        color: var(--el-text-color-primary);
      }
      span {
        color: var(--el-color-primary);
      }
    }
  }
</style>
